<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户中心 - 外卖平台</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: #f5f5f5;
            color: #333;
        }
        
        .header {
            background: white;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 20px 0;
            margin-bottom: 30px;
        }
        
        .header-content {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .header h1 {
            color: #ff6b6b;
            font-size: 28px;
        }
        
        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
        }
        
        .btn-primary {
            background: #ff6b6b;
            color: white;
        }
        
        .btn-primary:hover {
            background: #ee5a24;
            transform: translateY(-2px);
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #5a6268;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
        }
        
        .tabs {
            display: flex;
            background: white;
            border-radius: 12px;
            padding: 4px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .tab {
            flex: 1;
            padding: 15px;
            border: none;
            background: transparent;
            cursor: pointer;
            font-size: 16px;
            font-weight: 600;
            color: #666;
            border-radius: 8px;
            transition: all 0.3s ease;
        }
        
        .tab.active {
            background: #ff6b6b;
            color: white;
            box-shadow: 0 2px 10px rgba(255, 107, 107, 0.3);
        }
        
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
        }
        
        .merchants-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }
        
        .merchant-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
            cursor: pointer;
        }
        
        .merchant-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 20px rgba(0,0,0,0.15);
        }
        
        .merchant-image {
            width: 100%;
            height: 200px;
            border-radius: 8px;
            overflow: hidden;
            margin-bottom: 15px;
        }
        
        .merchant-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .merchant-info h3 {
            color: #333;
            margin-bottom: 10px;
            font-size: 20px;
        }
        
        .merchant-rating {
            display: flex;
            align-items: center;
            gap: 5px;
            margin-bottom: 10px;
        }
        
        .merchant-rating .stars {
            color: #ffc107;
        }
        
        .merchant-rating .rating {
            color: #666;
            font-size: 14px;
        }
        
        .merchant-details {
            color: #666;
            font-size: 14px;
            margin-bottom: 15px;
        }
        
        .merchant-details p {
            margin-bottom: 5px;
        }
        
        .merchant-tags {
            display: flex;
            gap: 5px;
            flex-wrap: wrap;
            margin-bottom: 15px;
        }
        
        .tag {
            background: #f8f9fa;
            color: #666;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 12px;
        }
        
        .dishes-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }
        
        .dish-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
        }
        
        .dish-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 20px rgba(0,0,0,0.15);
        }
        
        .dish-image {
            width: 100%;
            height: 200px;
            border-radius: 8px;
            overflow: hidden;
            margin-bottom: 15px;
        }
        
        .dish-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .dish-info h3 {
            color: #333;
            margin-bottom: 10px;
            font-size: 18px;
        }
        
        .dish-price {
            color: #ff6b6b;
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        
        .dish-category {
            background: #f8f9fa;
            color: #666;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            display: inline-block;
            margin-bottom: 10px;
        }
        
        .dish-description {
            color: #666;
            font-size: 14px;
            line-height: 1.5;
            margin-bottom: 15px;
        }
        
        .dish-actions {
            display: flex;
            gap: 10px;
        }
        
        .add-to-cart-btn {
            background: #28a745;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
        }
        
        .orders-list {
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .order-card {
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 15px;
            transition: all 0.3s ease;
        }
        
        .order-card:hover {
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .order-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .order-id {
            font-weight: bold;
            color: #333;
        }
        
        .order-status {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .status-pending {
            background: #fff3cd;
            color: #856404;
        }
        
        .status-preparing {
            background: #d1ecf1;
            color: #0c5460;
        }
        
        .status-ready {
            background: #d4edda;
            color: #155724;
        }
        
        .status-delivering {
            background: #cce5ff;
            color: #004085;
        }
        
        .status-completed {
            background: #e2e3e5;
            color: #383d41;
        }
        
        .order-content {
            margin-bottom: 15px;
        }
        
        .order-content p {
            margin-bottom: 5px;
            color: #666;
        }
        
        .back-btn {
            position: fixed;
            top: 20px;
            left: 20px;
            background: rgba(255, 107, 107, 0.8);
            border: none;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            cursor: pointer;
            color: white;
            font-size: 20px;
            transition: all 0.3s ease;
            z-index: 1000;
        }
        
        .back-btn:hover {
            background: #ff6b6b;
            transform: scale(1.1);
        }
        
        .hidden {
            display: none;
        }
        
        .message {
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-weight: 500;
            text-align: center;
        }
        
        .message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
    </style>
</head>
<body>
    <button class="back-btn" onclick="goBack()">←</button>
    
    <div class="header">
        <div class="header-content">
            <h1>👤 用户中心</h1>
            <div class="user-info">
                <span id="userName">用户名</span>
                <button class="btn btn-secondary" onclick="logout()">退出登录</button>
            </div>
        </div>
    </div>
    
    <div class="container">
        <div id="message"></div>
        
        <div class="tabs">
            <button class="tab active" onclick="showTab('merchants')">🏪 浏览商家</button>
            <button class="tab" onclick="showTab('dishes')">🍽️ 菜品推荐</button>
            <button class="tab" onclick="showTab('cart')">🛒 购物车</button>
            <button class="tab" onclick="showTab('orders')">📋 我的订单</button>
            <button class="tab" onclick="showTab('orderTracking')">📍 订单跟踪</button>
            <button class="tab" onclick="showTab('profile')">👤 个人资料</button>
        </div>
        
        <!-- 浏览商家 -->
        <div id="merchants" class="tab-content active">
            <h2>附近商家</h2>
            <div class="merchants-grid" id="merchantsGrid">
                <!-- 商家将通过JavaScript动态加载 -->
            </div>
        </div>
        
        <!-- 菜品推荐 -->
        <div id="dishes" class="tab-content">
            <h2>热门菜品</h2>
            <div class="dishes-grid" id="dishesGrid">
                <!-- 菜品将通过JavaScript动态加载 -->
            </div>
        </div>
        
        <!-- 我的订单 -->
        <div id="orders" class="tab-content">
            <h2>我的订单</h2>
            <div class="orders-list" id="ordersList">
                <!-- 订单将通过JavaScript动态加载 -->
            </div>
        </div>
        
        <!-- 订单跟踪 -->
        <div id="orderTracking" class="tab-content">
            <h2>订单跟踪</h2>
            <div class="tracking-container" id="trackingContainer">
                <!-- 订单跟踪信息将通过JavaScript动态加载 -->
            </div>
        </div>
        
        <!-- 购物车 -->
        <div id="cart" class="tab-content">
            <h2>购物车</h2>
            <div id="cartContent" style="background: white; border-radius: 12px; padding: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                <!-- 购物车内容将通过JavaScript动态加载 -->
            </div>
        </div>
        
        <!-- 个人资料 -->
        <div id="profile" class="tab-content">
            <h2>个人资料</h2>
            <div style="background: white; border-radius: 12px; padding: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                <div class="profile-section">
                    <h3>基本信息</h3>
                    <div class="form-group">
                        <label>用户名</label>
                        <input type="text" id="profileUsername" value="">
                    </div>
                    <div class="form-group">
                        <label>手机号</label>
                        <input type="text" id="profilePhone" value="">
                    </div>
                    <div class="form-group">
                        <label>邮箱</label>
                        <input type="email" id="profileEmail" value="">
                    </div>
                    <button class="btn btn-primary" onclick="updateProfile()">保存修改</button>
                </div>
                
                <div class="profile-section" style="margin-top: 30px;">
                    <h3>收货地址</h3>
                    <div id="addressList">
                        <!-- 地址列表 -->
                    </div>
                    <button class="btn btn-secondary" onclick="addAddress()">添加新地址</button>
                </div>
            </div>
        </div>
    </div>

    <script src="database.js"></script>
    <script>
        let currentUser = null;
        
        // 页面加载时初始化
        window.onload = function() {
            checkLoginStatus();
            loadMerchants();
            loadDishes();
            loadOrders();
            updateCartDisplay();
            loadProfile();
            loadAddresses();
        };
        
        function loadProfile() {
            if (currentUser) {
                document.getElementById('profileUsername').value = currentUser.username || '';
                document.getElementById('profilePhone').value = currentUser.phone || '';
                document.getElementById('profileEmail').value = currentUser.email || '';
            }
        }
        
        function checkLoginStatus() {
            const savedUser = localStorage.getItem('currentUser');
            if (savedUser) {
                currentUser = JSON.parse(savedUser);
                if (currentUser.type !== 'user') {
                    alert('您没有权限访问用户中心！');
                    window.location.href = 'home.html';
                    return;
                }
                document.getElementById('userName').textContent = currentUser.name;
            } else {
                alert('请先登录！');
                window.location.href = 'login.html';
            }
        }
        
        function showTab(tabName) {
            // 隐藏所有标签页内容
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            
            // 移除所有标签页的激活状态
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // 显示选中的标签页
            document.getElementById(tabName).classList.add('active');
            
            // 激活对应的标签按钮
            event.target.classList.add('active');
            
            // 根据标签页加载相应数据
            switch(tabName) {
                case 'merchants':
                    loadMerchants();
                    break;
                case 'dishes':
                    loadDishes();
                    break;
                case 'cart':
                    updateCartDisplay();
                    break;
                case 'orders':
                    loadOrders();
                    break;
                case 'orderTracking':
                    loadOrderTracking();
                    break;
                case 'profile':
                    loadProfile();
                    break;
            }
        }
        
        function loadMerchants() {
            const merchants = db.getMerchants();
            const merchantsGrid = document.getElementById('merchantsGrid');
            
            if (merchants.length === 0) {
                merchantsGrid.innerHTML = `
                    <div style="grid-column: 1 / -1; text-align: center; padding: 40px; color: #666;">
                        <p>暂无商家</p>
                    </div>
                `;
                return;
            }
            
            merchantsGrid.innerHTML = merchants.map(merchant => `
                <div class="merchant-card" onclick="viewMerchant(${merchant.id})">
                    <div class="merchant-image">
                        <img src="${merchant.image}" alt="${merchant.name}" onerror="this.src='https://via.placeholder.com/350x200?text=商家图片'">
                    </div>
                    <div class="merchant-info">
                        <h3>${merchant.name}</h3>
                        <div class="merchant-rating">
                            <span class="stars">⭐⭐⭐⭐⭐</span>
                            <span class="rating">${merchant.rating}</span>
                        </div>
                        <div class="merchant-details">
                            <p>${merchant.description}</p>
                            <p>配送时间: ${merchant.deliveryTime}</p>
                            <p>配送费: ¥${merchant.deliveryFee}</p>
                            <p>起送价: ¥${merchant.minOrder}</p>
                        </div>
                        <div class="merchant-tags">
                            ${merchant.tags.map(tag => `<span class="tag">${tag}</span>`).join('')}
                        </div>
                    </div>
                </div>
            `).join('');
        }
        
        function loadDishes() {
            const dishes = db.getDishes();
            const dishesGrid = document.getElementById('dishesGrid');
            
            if (dishes.length === 0) {
                dishesGrid.innerHTML = `
                    <div style="grid-column: 1 / -1; text-align: center; padding: 40px; color: #666;">
                        <p>暂无菜品</p>
                    </div>
                `;
                return;
            }
            
            dishesGrid.innerHTML = dishes.map(dish => `
                <div class="dish-card">
                    <div class="dish-image">
                        <img src="${dish.image}" alt="${dish.name}" onerror="this.src='https://via.placeholder.com/300x200?text=菜品图片'">
                    </div>
                    <div class="dish-info">
                        <h3>${dish.name}</h3>
                        <div class="dish-price">¥${dish.price}</div>
                        <div class="dish-category">${dish.category}</div>
                        <div class="dish-description">${dish.description}</div>
                        <div style="margin-bottom: 15px;">
                            <span style="color: #666; font-size: 12px;">评分: ${dish.rating} ⭐</span>
                            <span style="color: #666; font-size: 12px; margin-left: 10px;">销量: ${dish.sales}</span>
                        </div>
                        <div class="dish-actions">
                            <button class="add-to-cart-btn" onclick="addToCart(${dish.id})">加入购物车</button>
                        </div>
                    </div>
                </div>
            `).join('');
        }
        
        function loadOrders() {
            if (!currentUser) return;
            
            const orders = db.getOrdersByUser(currentUser.id);
            const ordersList = document.getElementById('ordersList');
            
            if (orders.length === 0) {
                ordersList.innerHTML = `
                    <div style="text-align: center; padding: 40px; color: #666;">
                        <p>暂无订单</p>
                    </div>
                `;
                return;
            }
            
            ordersList.innerHTML = orders.map(order => `
                <div class="order-card">
                    <div class="order-header">
                        <span class="order-id">订单号: #${order.id}</span>
                        <span class="order-status status-${order.status}">${getStatusText(order.status)}</span>
                    </div>
                    <div class="order-content">
                        <p><strong>商家:</strong> ${db.getMerchantById(order.merchantId)?.name || '未知商家'}</p>
                        <p><strong>菜品:</strong> ${order.dishes.map(dish => `${dish.name} x${dish.quantity}`).join(', ')}</p>
                        <p><strong>总价:</strong> ¥${order.finalPrice}</p>
                        <p><strong>下单时间:</strong> ${order.orderTime}</p>
                        <p><strong>配送地址:</strong> ${order.deliveryAddress}</p>
                        ${order.riderName ? `<p><strong>骑手:</strong> ${order.riderName}</p>` : ''}
                    </div>
                </div>
            `).join('');
        }
        
        function getStatusText(status) {
            const statusMap = {
                'pending': '待处理',
                'preparing': '制作中',
                'ready': '待配送',
                'delivering': '配送中',
                'completed': '已完成'
            };
            return statusMap[status] || status;
        }
        
        function viewMerchant(merchantId) {
            // 跳转到商家详情页面
            showMessage('商家详情功能开发中...', 'success');
        }
        
        let cart = JSON.parse(localStorage.getItem('cart') || '[]');
        
        function addToCart(dishId) {
            const dish = db.getDishById(dishId);
            if (!dish) return;
            
            const existingItem = cart.find(item => item.id === dishId);
            if (existingItem) {
                existingItem.quantity += 1;
            } else {
                cart.push({
                    id: dish.id,
                    name: dish.name,
                    price: dish.price,
                    image: dish.image,
                    quantity: 1,
                    merchantId: dish.merchantId
                });
            }
            
            localStorage.setItem('cart', JSON.stringify(cart));
            showMessage('已添加到购物车！', 'success');
            updateCartDisplay();
        }
        
        function updateCartDisplay() {
            const cartContent = document.getElementById('cartContent');
            if (!cartContent) return;
            
            if (cart.length === 0) {
                cartContent.innerHTML = `
                    <div style="text-align: center; padding: 40px; color: #666;">
                        <p>购物车是空的</p>
                        <p>去浏览商家添加喜欢的菜品吧！</p>
                    </div>
                `;
                return;
            }
            
            const total = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
            
            cartContent.innerHTML = `
                <div class="cart-items">
                    ${cart.map(item => `
                        <div class="cart-item" style="display: flex; align-items: center; padding: 15px; border-bottom: 1px solid #eee;">
                            <img src="${item.image}" alt="${item.name}" style="width: 60px; height: 60px; border-radius: 8px; object-fit: cover; margin-right: 15px;">
                            <div style="flex: 1;">
                                <h4 style="margin: 0 0 5px 0;">${item.name}</h4>
                                <p style="color: #ff6b6b; font-weight: bold; margin: 0;">¥${item.price}</p>
                            </div>
                            <div style="display: flex; align-items: center; gap: 10px;">
                                <button onclick="updateQuantity(${item.id}, -1)" style="background: #f8f9fa; border: 1px solid #ddd; border-radius: 4px; width: 30px; height: 30px;">-</button>
                                <span style="min-width: 30px; text-align: center;">${item.quantity}</span>
                                <button onclick="updateQuantity(${item.id}, 1)" style="background: #f8f9fa; border: 1px solid #ddd; border-radius: 4px; width: 30px; height: 30px;">+</button>
                                <button onclick="removeFromCart(${item.id})" style="background: #dc3545; color: white; border: none; border-radius: 4px; padding: 5px 10px; margin-left: 10px;">删除</button>
                            </div>
                        </div>
                    `).join('')}
                </div>
                <div style="border-top: 2px solid #eee; padding: 20px 0; margin-top: 20px;">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                        <h3>总计: ¥${total}</h3>
                    </div>
                    <button class="btn btn-primary" onclick="checkout()" style="width: 100%; padding: 15px; font-size: 16px;">立即结算</button>
                </div>
            `;
        }
        
        function updateQuantity(dishId, change) {
            const item = cart.find(item => item.id === dishId);
            if (item) {
                item.quantity += change;
                if (item.quantity <= 0) {
                    cart = cart.filter(item => item.id !== dishId);
                }
                localStorage.setItem('cart', JSON.stringify(cart));
                updateCartDisplay();
            }
        }
        
        function removeFromCart(dishId) {
            cart = cart.filter(item => item.id !== dishId);
            localStorage.setItem('cart', JSON.stringify(cart));
            updateCartDisplay();
            showMessage('已从购物车移除', 'success');
        }
        
        function checkout() {
            if (cart.length === 0) {
                showMessage('购物车是空的！', 'error');
                return;
            }
            
            const total = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
            const deliveryFee = 5;
            const finalTotal = total + deliveryFee;
            
            // 创建订单
            const order = {
                userId: currentUser.id,
                merchantId: cart[0].merchantId,
                dishes: cart.map(item => ({
                    id: item.id,
                    name: item.name,
                    price: item.price,
                    quantity: item.quantity
                })),
                totalPrice: total,
                deliveryFee: deliveryFee,
                finalPrice: finalTotal,
                status: 'pending',
                riderStatus: 'available',
                orderTime: new Date().toLocaleString(),
                deliveryAddress: '北京市朝阳区xxx小区',
                customerPhone: currentUser.phone || '13800138000',
                customerName: currentUser.name || currentUser.username,
                notes: ''
            };
            
            db.addOrder(order);
            
            // 清空购物车
            cart = [];
            localStorage.setItem('cart', JSON.stringify(cart));
            
            showMessage('订单提交成功！', 'success');
            updateCartDisplay();
            loadOrders();
        }
        
        function updateProfile() {
            const username = document.getElementById('profileUsername').value;
            const phone = document.getElementById('profilePhone').value;
            const email = document.getElementById('profileEmail').value;
            
            if (currentUser) {
                db.updateUser(currentUser.id, {
                    username: username,
                    phone: phone,
                    email: email
                });
                
                // 更新当前用户信息
                currentUser.username = username;
                currentUser.phone = phone;
                currentUser.email = email;
                localStorage.setItem('currentUser', JSON.stringify(currentUser));
                
                showMessage('个人信息更新成功！', 'success');
            }
        }
        
        function addAddress() {
            const address = prompt('请输入新地址：');
            if (address && currentUser) {
                if (!currentUser.addresses) {
                    currentUser.addresses = [];
                }
                currentUser.addresses.push({
                    id: Date.now(),
                    address: address,
                    isDefault: currentUser.addresses.length === 0
                });
                
                db.updateUser(currentUser.id, { addresses: currentUser.addresses });
                localStorage.setItem('currentUser', JSON.stringify(currentUser));
                loadAddresses();
                showMessage('地址添加成功！', 'success');
            }
        }
        
        function loadAddresses() {
            const addressList = document.getElementById('addressList');
            if (!addressList || !currentUser) return;
            
            const addresses = currentUser.addresses || [];
            
            if (addresses.length === 0) {
                addressList.innerHTML = '<p style="color: #666;">暂无收货地址</p>';
                return;
            }
            
            addressList.innerHTML = addresses.map(addr => `
                <div style="border: 1px solid #eee; border-radius: 8px; padding: 15px; margin-bottom: 10px;">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <div>
                            <p style="margin: 0; font-weight: 600;">${addr.address}</p>
                            ${addr.isDefault ? '<span style="background: #ff6b6b; color: white; padding: 2px 8px; border-radius: 12px; font-size: 12px;">默认</span>' : ''}
                        </div>
                        <div>
                            <button onclick="setDefaultAddress(${addr.id})" style="background: #28a745; color: white; border: none; border-radius: 4px; padding: 5px 10px; margin-right: 5px;">设为默认</button>
                            <button onclick="deleteAddress(${addr.id})" style="background: #dc3545; color: white; border: none; border-radius: 4px; padding: 5px 10px;">删除</button>
                        </div>
                    </div>
                </div>
            `).join('');
        }
        
        function setDefaultAddress(addressId) {
            if (currentUser && currentUser.addresses) {
                currentUser.addresses.forEach(addr => {
                    addr.isDefault = addr.id === addressId;
                });
                
                db.updateUser(currentUser.id, { addresses: currentUser.addresses });
                localStorage.setItem('currentUser', JSON.stringify(currentUser));
                loadAddresses();
                showMessage('默认地址设置成功！', 'success');
            }
        }
        
        function deleteAddress(addressId) {
            if (confirm('确定要删除这个地址吗？')) {
                if (currentUser && currentUser.addresses) {
                    currentUser.addresses = currentUser.addresses.filter(addr => addr.id !== addressId);
                    
                    db.updateUser(currentUser.id, { addresses: currentUser.addresses });
                    localStorage.setItem('currentUser', JSON.stringify(currentUser));
                    loadAddresses();
                    showMessage('地址删除成功！', 'success');
                }
            }
        }
        
        // 订单跟踪功能
        function loadOrderTracking() {
            if (!currentUser) return;
            
            const orders = db.getOrdersByUser(currentUser.id);
            const trackingOrders = orders.filter(order => 
                order.status === 'accepted' || order.status === 'delivering'
            );
            
            const trackingContainer = document.getElementById('trackingContainer');
            
            if (trackingOrders.length === 0) {
                trackingContainer.innerHTML = `
                    <div style="text-align: center; padding: 40px; color: #666;">
                        <h3>📍 暂无配送中的订单</h3>
                        <p>当前没有正在配送的订单</p>
                    </div>
                `;
                return;
            }
            
            trackingContainer.innerHTML = trackingOrders.map(order => `
                <div class="tracking-card" style="background: white; border-radius: 12px; padding: 20px; margin-bottom: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                    <div class="tracking-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                        <h3>订单 #${order.id}</h3>
                        <span class="status-badge status-${order.status}" style="padding: 4px 12px; border-radius: 20px; font-size: 12px; font-weight: 600;">
                            ${getStatusText(order.status)}
                        </span>
                    </div>
                    
                    <div class="order-info" style="margin-bottom: 15px;">
                        <p><strong>商家:</strong> ${db.getMerchantById(order.merchantId)?.name || '未知商家'}</p>
                        <p><strong>配送地址:</strong> ${order.deliveryAddress}</p>
                        <p><strong>预计送达:</strong> ${order.estimatedTime || 25}分钟</p>
                        ${order.riderName ? `<p><strong>配送骑手:</strong> ${order.riderName}</p>` : ''}
                    </div>
                    
                    <div class="rider-location" id="riderLocation_${order.id}" style="margin-bottom: 15px;">
                        ${order.riderId ? getRiderLocationDisplay(order.riderId) : '<p style="color: #999;">等待骑手接单</p>'}
                    </div>
                    
                    <div class="tracking-actions" style="display: flex; gap: 10px;">
                        <button class="btn btn-primary" onclick="refreshRiderLocation(${order.id})">🔄 刷新位置</button>
                        <button class="btn btn-secondary" onclick="showRoute(${order.id})">🗺️ 查看路线</button>
                    </div>
                </div>
            `).join('');
        }
        
        function getRiderLocationDisplay(riderId) {
            const location = db.getRiderLocationById(riderId);
            
            if (!location) {
                return '<p style="color: #999;">骑手位置信息暂不可用</p>';
            }
            
            const timeAgo = getTimeAgo(new Date(location.timestamp));
            
            return `
                <div style="background: #f8f9fa; padding: 15px; border-radius: 8px;">
                    <h4>📍 骑手位置</h4>
                    <p><strong>坐标:</strong> ${location.latitude.toFixed(6)}, ${location.longitude.toFixed(6)}</p>
                    <p><strong>精度:</strong> ${Math.round(location.accuracy)}米</p>
                    <p><strong>状态:</strong> ${getRiderStatusText(location.status)}</p>
                    <p><strong>最后更新:</strong> ${timeAgo}</p>
                </div>
            `;
        }
        
        function getRiderStatusText(status) {
            const statusMap = {
                'online': '在线接单',
                'busy': '配送中',
                'offline': '离线'
            };
            return statusMap[status] || status;
        }
        
        function getTimeAgo(date) {
            const now = new Date();
            const diff = now - date;
            const minutes = Math.floor(diff / 60000);
            
            if (minutes < 1) return '刚刚';
            if (minutes < 60) return `${minutes}分钟前`;
            
            const hours = Math.floor(minutes / 60);
            if (hours < 24) return `${hours}小时前`;
            
            const days = Math.floor(hours / 24);
            return `${days}天前`;
        }
        
        function refreshRiderLocation(orderId) {
            const order = db.getOrderById(orderId);
            if (!order || !order.riderId) {
                showMessage('该订单暂无配送骑手！', 'error');
                return;
            }
            
            const locationElement = document.getElementById(`riderLocation_${orderId}`);
            if (locationElement) {
                locationElement.innerHTML = getRiderLocationDisplay(order.riderId);
                showMessage('位置信息已刷新！', 'success');
            }
        }
        
        function showRoute(orderId) {
            const order = db.getOrderById(orderId);
            if (!order || !order.riderId) {
                showMessage('该订单暂无配送骑手！', 'error');
                return;
            }
            
            const riderLocation = db.getRiderLocationById(order.riderId);
            if (!riderLocation) {
                showMessage('骑手位置信息暂不可用！', 'error');
                return;
            }
            
            // 模拟路线显示
            const routeInfo = `
                起点: 商家位置 (${db.getMerchantById(order.merchantId)?.name || '未知商家'})
                终点: ${order.deliveryAddress}
                骑手当前位置: ${riderLocation.latitude.toFixed(4)}, ${riderLocation.longitude.toFixed(4)}
                预计剩余时间: ${order.estimatedTime || 25}分钟
            `;
            
            showMessage(`配送路线信息:\n${routeInfo}`, 'success');
            console.log('配送路线:', routeInfo);
        }
        
        function showMessage(text, type) {
            const messageDiv = document.getElementById('message');
            messageDiv.innerHTML = `<div class="message ${type}">${text}</div>`;
            setTimeout(() => {
                messageDiv.innerHTML = '';
            }, 3000);
        }
        
        function logout() {
            localStorage.removeItem('currentUser');
            window.location.href = 'home.html';
        }
        
        function goBack() {
            window.location.href = 'home.html';
        }
    </script>
</body>
</html>
